package com.rednote.service.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rednote.entity.UserLikes;
import com.rednote.mapper.UserLikesMapper;
import com.rednote.mapper.PostsMapper;
import com.rednote.mapper.CommentsMapper;
import com.rednote.entity.Posts;
import com.rednote.entity.Comments;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LikeDataSyncRunner implements CommandLineRunner {

    @Autowired
    private UserLikesMapper userLikesMapper;
    @Autowired
    private PostsMapper postsMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String POST_LIKE_KEY_PREFIX = "post:like:";
    private static final String COMMENT_LIKE_KEY_PREFIX = "comment:like:";
    private static final String POST_LIKE_COUNT_KEY_PREFIX = "post:like:count:";
    private static final String COMMENT_LIKE_COUNT_KEY_PREFIX = "comment:like:count:";

    @Override
    public void run(String... args) throws Exception {
        syncLikesToRedis();
    }

    public void syncLikesToRedis() {
        System.out.println("开始同步点赞数据到Redis...");

        // 1. 查询所有点赞记录
        List<UserLikes> likesList = userLikesMapper.selectList(new QueryWrapper<>());

        // 2. 逐条同步
        for (UserLikes like : likesList) {
            Integer userId = like.getUserId();
            Integer targetId = like.getTargetId();
            Integer targetType = like.getTargetType(); // 0帖子 1评论

            String setKey = targetType == 0 ? POST_LIKE_KEY_PREFIX + targetId : COMMENT_LIKE_KEY_PREFIX + targetId;
            String countKey = targetType == 0 ? POST_LIKE_COUNT_KEY_PREFIX + targetId : COMMENT_LIKE_COUNT_KEY_PREFIX + targetId;

            // 2.1 同步点赞集合：如果Redis中没有该用户，添加
            Boolean isMember = redisTemplate.opsForSet().isMember(setKey, String.valueOf(userId));
            if (Boolean.FALSE.equals(isMember)) {
                redisTemplate.opsForSet().add(setKey, String.valueOf(userId));
            }

            // 2.2 同步点赞数量
            String countStr = redisTemplate.opsForValue().get(countKey);
            if (countStr == null) {
                // 从数据库查
                int count = 0;
                if (targetType == 0) {
                    Posts post = postsMapper.selectById(targetId);
                    count = (post != null && post.getLikeCount() != null) ? post.getLikeCount() : 0;
                } else {
                    Comments comment = commentsMapper.selectById(targetId);
                    count = (comment != null && comment.getLikeCount() != null) ? comment.getLikeCount() : 0;
                }
                count = Math.max(count, 0); // 防止负数
                redisTemplate.opsForValue().set(countKey, String.valueOf(count), 1, TimeUnit.HOURS);
            }
        }

        System.out.println("点赞数据同步完成！");
    }
}
